package com.itany.shop.filter;

import com.itany.shop.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 石小俊
 * @date 2023年10月30日 14:48
 */
//@WebFilter("/*")
public class CheckLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取当前请求
        String path = request.getServletPath();
        System.out.println("path:"+path);
        // 遇到注册、登录、主页相关的功能无需登录,直接放行
        if("/jsp/register.jsp".equals(path) || "/jsp/login.jsp".equals(path) || "/jsp/main.jsp".equals(path) || "/index.jsp".equals(path) || path.endsWith(".user") || "/showCode".equals(path) || "/findAll.product".equals(path) || "/js/jquery-3.4.1.min.js".equals(path)){
            // 直接放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        // 除了上述请求以外的所有请求都必须登录后才能访问
        // 判断当前用户是否已经登录
        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            // 如果在session中没有取到user,则表示尚未登录
            // 此时可以转发到登录页面,而不进行放行
            request.setAttribute("loginMsg","您尚未登录,请登录后再进行操作");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
            return;
        }
        // 如果用户已经登录了,则直接放行
        filterChain.doFilter(servletRequest,servletResponse);

    }

    @Override
    public void destroy() {

    }
}
